import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import 'dart:typed_data';
import 'mediaGridItem.dart';

class MediaGrid extends StatelessWidget {
  final List<dynamic> mediaList; // AssetEntity
  final List<int> selectedIndexes; // 选中的索引
  final int maxSelect;
  final Function(int index) onTap;
  final bool isVideo;
  final ScrollController? scrollController;

  // 添加静态缓存
  static final Map<String, Uint8List> _thumbnailCache = {};

  const MediaGrid({
    Key? key,
    required this.mediaList,
    required this.selectedIndexes,
    required this.onTap,
    this.maxSelect = 18,
    this.isVideo = false,
    this.scrollController,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      controller: scrollController,
      padding: EdgeInsets.zero,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
        crossAxisSpacing: 2,
        mainAxisSpacing: 2,
      ),
      itemCount: mediaList.length,
      itemBuilder: (context, index) {
        try {
          final isSelected = selectedIndexes.contains(index);
          final selectOrder =
              isSelected ? selectedIndexes.indexOf(index) + 1 : null;
          final isDisabled = !isSelected && selectedIndexes.length >= maxSelect;
          final AssetEntity entity = mediaList[index];
          String? duration;
          if (entity.type == AssetType.video) {
            final d = entity.videoDuration;
            duration = d != null ? _formatDuration(d) : null;
          }
          return MediaGridItem(
            key: ValueKey(entity.id),
            entity: entity,
            isSelected: isSelected,
            selectOrder: selectOrder,
            isDisabled: isDisabled,
            isVideo: entity.type == AssetType.video,
            duration: duration,
            onTap: () => onTap(index),
          );
        } catch (e) {
          return Container(
            color: Colors.red,
            child: Center(child: Icon(Icons.error, color: Colors.white)),
          );
        }
      },
    );
  }

  String _formatDuration(Duration d) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(d.inMinutes.remainder(60));
    final seconds = twoDigits(d.inSeconds.remainder(60));
    return "${d.inHours > 0 ? '${twoDigits(d.inHours)}:' : ''}$minutes:$seconds";
  }

  Future<Uint8List?> _getCachedThumbnail(AssetEntity entity) async {
    final key = "${entity.id}_${ThumbnailSize(200, 200).toString()}";
    if (_thumbnailCache.containsKey(key)) {
      return _thumbnailCache[key];
    } else {
      final data = await entity.thumbnailDataWithSize(ThumbnailSize(200, 200));
      if (data != null) {
        _thumbnailCache[key] = data;
      }
      return data;
    }
  }
}
